package cn.myblog.ainblog.conroller.backstage;

import cn.myblog.ainblog.dto.ArticleDTO;
import cn.myblog.ainblog.model.ArticleModel;
import cn.myblog.ainblog.model.CategoryModel;
import cn.myblog.ainblog.model.TagModel;
import cn.myblog.ainblog.service.ArticleService;
import cn.myblog.ainblog.service.CategoryService;
import cn.myblog.ainblog.service.CommentService;
import cn.myblog.ainblog.service.TagService;
import cn.myblog.ainblog.vo.ArticleAndCategoryVO;
import cn.myblog.ainblog.vo.ArticleAndTagVO;
import cn.myblog.ainblog.vo.ArticleCategoryVO;
import cn.myblog.ainblog.vo.PageVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Dovaior
 * @Description 关于Article的控制器
 * @create 2021-04-13 16:27
 **/
@Controller
@RequestMapping("/backstage")
public class BackstageArticleController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private TagService tagService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CommentService commentService;

    /**
     * 跳转至添加页面
     * @param model 将封装的信息发送至前端
     * @return return 跳转页面
     */
    @GetMapping("/addArticle")
    public String addArticle(Model model){
        List<CategoryModel> categoryModels = categoryService.selectAll();
        model.addAttribute("categoryModels",categoryModels);
        List<TagModel> tagModels = tagService.selectAllTag();
        model.addAttribute("tagModels",tagModels);
        return "backstage/backstage-addArticle";
    }

    /**
     * 添加博文
     * @param articleDTO 从前端接收的数据
     * @param categoryName 从前端接收的分类名（ID值）
     * @param tagName 从前端接收到的标签名（ID值）
     * @return return 跳转页面
     */
    @PostMapping("/insertArticle")
    public String insertArticle(ArticleDTO articleDTO,String categoryName,String tagName){
        //设置添加博文的创建时间
        Date utilDate = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String articleDate = format.format(utilDate);
        articleDTO.setArticleDate(articleDate);
        //复制
        ArticleModel articleModel = new ArticleModel();
        BeanUtils.copyProperties(articleDTO,articleModel);
        //将接收到的tagName转换为List
        List<String> tagNames = Arrays.asList(tagName.split(","));
        //执行更新
        articleService.addArticle(articleModel,categoryName,tagNames);
        //重定向去addArticle请求
        return "redirect:/backstage/queryArticleList/1";
    }

    /**
     * 分页查询
     * @param current 当前页码
     * @param model 封装信息
     * @return 返回页面
     */
    @GetMapping("/queryArticleList/{current}")
    public String queryArticleList(@PathVariable Integer current,Model model){
        //每页四条数据
        Integer size = 4;
        //封装page信息（当前页，每页条目数）
        IPage<ArticleCategoryVO> page = new Page<>(current,size);
        //进行查询（将封装的page信息填充到sql语句之后）
        articleService.selectArticleAndCategoryListPage(page);
        PageVO<ArticleCategoryVO> articleCategoryVO = new PageVO<>();
        //为PageVO赋值
        articleCategoryVO.setSize(size);
        articleCategoryVO.setCurrent(current);
        //将总条目数转换为总页数
        Long pageSize = page.getTotal() % size;
        if (pageSize == 0){
            //整除总页数
            articleCategoryVO.setTotal(page.getTotal()/size);
        }else{
            //不能整除，总页数加一
            articleCategoryVO.setTotal((page.getTotal()/size)+1);
        }
        //封装出来的信息
        articleCategoryVO.setPageList(page.getRecords());
        //给前端返回
        model.addAttribute("articleCategoryVO",articleCategoryVO);
        return "backstage/backstage-articleList";
    }

    /**
     * 根据博文ID值进行删除
     * @param articleId 传递过来的博文ID
     * @return 返回标识
     */
    @ResponseBody
    @GetMapping("/deleteArticleById/{articleId}")
    public boolean deleteArticleById(@PathVariable String articleId){
        boolean flag = false;
        int i = articleService.deleteArticle(articleId);
        if (i == 1){
            //删除成功
            flag = true;
        }else{
            //删除失败
            flag = false;
        }
        return flag;
    }

    /**
     * 根据ID值查询关于博文的全部信息
     * @param articleId 传递过来的ID值
     * @param current 当前页码：传递当前页码用于更新完成以后的跳转
     * @param model 用于封装数据的model
     * @return 返回页面
     */
    @GetMapping("/updateArticle/{articleId}/{current}")
    public String updateArticle(@PathVariable String articleId,@PathVariable Integer current,Model model){
        //回显分类
        List<CategoryModel> categoryModels = categoryService.selectAll();
        model.addAttribute("categoryModels",categoryModels);
        //回显标签
        List<TagModel> tagModels = tagService.selectAllTag();
        model.addAttribute("tagModels",tagModels);
        //传递当前页码
        model.addAttribute("current",current);
        //获取博文全部信息
        Map<String, Object> articleMap = articleService.queryArticleById(articleId);
        //分离博文表中的信息
        ArticleModel articleModel = (ArticleModel) articleMap.get("articleModel");
        model.addAttribute("articleModel",articleModel);
        //获取对应的分类信息
        ArticleAndCategoryVO articleAndCategoryVO = (ArticleAndCategoryVO) articleMap.get("articleAndCategoryVO");
        model.addAttribute("articleAndCategoryVO",articleAndCategoryVO);
        //获取对应的标签信息
        ArticleAndTagVO articleAndTagVO = (ArticleAndTagVO) articleMap.get("articleAndTagVO");
        //分离标签名
        List<String> tagList = new ArrayList<>();
        for (TagModel tag : articleAndTagVO.getTempTagModel()){
            tagList.add(tag.getTagName());
        }
        model.addAttribute("tagList",tagList);
        return "backstage/backstage-updateArticle";
    }

    /**
     * 更新信息
     * @param current 当前页码：用于更新完成以后跳转到当前页码页
     * @param articleDTO 前端接收的article实体类
     * @param categoryName 接收的分类ID
     * @param tagName 接收的标签ID的集合
     * @return
     */
    @PostMapping("/updateArticle/{current}")
    public String updateArticle(@PathVariable Integer current, ArticleDTO articleDTO,String categoryName,String tagName){
        ArticleModel articleModel = new ArticleModel();
        BeanUtils.copyProperties(articleDTO,articleModel);
        List<String> tagNames = Arrays.asList(tagName.split(","));
        articleService.updateArticle(articleModel,categoryName,tagNames);
        return "redirect:/backstage/queryArticleList/"+current;
    }

    /**
     *
     * @param articleId
     */
    @ResponseBody
    @GetMapping("/isQueryComment/{articleId}")
    public boolean isQueryComment(@PathVariable String articleId){
        List<Long> ids = commentService.queryCommentIdsByArticleId(articleId);
        if (ids.size() == 0){
            return true;
        }else{
            return false;
        }
    }
}
